﻿using K9Nano.Updater.Utils;

namespace K9Nano.Updater.Pipes;

public abstract class CommandPipeBase : UpdatePipeBase
{
    protected CommandPipeBase()
    {
        PipeName = "执行";
    }

    protected int? ExitCode;

    protected override bool CanInvoke(UpdateContext context)
    {
        return base.CanInvoke(context) && context.Package != null && !string.IsNullOrEmpty(GetCommand(context.Package!));
    }

    protected override Task InvokeCoreAsync(UpdateContext context, CancellationToken cancellation)
    {
        if (context.Package is null)
        {
            context.LogError("更新包元数据不存在");
            return Task.CompletedTask;
        }

        var command = GetCommand(context.Package);
        var args = GetCommandArgs(context.Package) ?? string.Empty;

        if (!string.IsNullOrEmpty(command))
        {
            context.LogInformation("开始执行命令：{command} {args}", command, args);
            ExitCode = ProcessUtils.Run(command, args, t =>
            {
                if (!string.IsNullOrEmpty(t)) context.LogInformation(t);
            });
            if (ExitCode != 0)
            {
                context.LogError("执行命令失败：{command} {args}，返回值为：{exitCode}", command, args, ExitCode);
                return Task.CompletedTask;
            }
            context.LogInformation("执行命令成功：{command} {args}，返回值为：{exitCode}", command, args, ExitCode);
        }

        return Task.CompletedTask;
    }


    protected abstract string? GetCommand(ReleaseMetadata package);

    protected abstract string? GetCommandArgs(ReleaseMetadata package);

}
